import { SafeAreaView, FlatList, Text, StyleSheet, View, TouchableOpacity, ActivityIndicator } from 'react-native'
import React, { Component, useState } from 'react'
import { connect } from 'react-redux'
import { SetUserInfo, SetToken } from "../../redux/features/appSlice"
import { Toast } from '@ant-design/react-native'
import { IconOutline } from "@ant-design/icons-react-native";
import { pTx } from "../../utils/dimensions"
import { signMessage } from 'react-native-web3-wallet';
import { schemaName } from "../../realm"
import { useRealm } from '@realm/react'
import Realm from "realm"
import ShadowCard from "../../utils/shadowCard"
import LinearGradient from 'react-native-linear-gradient';
import httpApi from "../../api"
import AsyncStorage from '@react-native-async-storage/async-storage';


const mapStateToProps = state => {
    return {
    }
}

const shuffle = (array) => {
    var currentIndex = array.length,
        temporaryValue,
        randomIndex
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}


function ShuffleMnemonic(props) {
    const { shuffleMnemonic, mnemonic } = props;
    const addshuffleMnemonic = (item) => {
        props.updateParentState({
            mnemonic: Array.from(new Set([...mnemonic, item]))
        });
    }
    return (
        <View style={styles.shuffleMnemonic}>
            {
                shuffleMnemonic.map((item, index) => {
                    return (
                        <Text key={index} style={[styles.shuffleMnemonicItem, mnemonic.indexOf(item) !== -1 ? styles.itemCurrent : ""]} onPress={() => addshuffleMnemonic(item)}>
                            {item}
                        </Text>
                    )
                })
            }
        </View>
    )
}
const ButtonFinishCreateWallet = (props) => {
    const [loading, setLoading] = useState(false)
    const realm = useRealm();
    const FinishCreateWallet = async () => {
        try {
            setLoading(true)
            if (props.mnemonic.toString() == props.wallet.mnemonic.toString()) {
                const sign = await signMessage(
                    JSON.stringify(props.route.params.wallet.keystore),
                    props.route.params.password,
                    httpApi.message,
                )
                const res = await httpApi.register({
                    nickname: "BNB-1",
                    signature: sign,
                    message: httpApi.message,
                    profilePhoto: httpApi.defaultAvatar
                })
                if (res.code == 20) {
                    realm.write(() => {
                        realm.create(schemaName.UserInfo, { ...res.data.UserInfo, Token: res.data.Token, Current: true }, true);
                        realm.create(schemaName.Wallet, {
                            _id: new Realm.BSON.UUID(),
                            address: props.route.params.wallet.address,
                            keystore: JSON.stringify(props.route.params.wallet.keystore),
                            name: "BNB-1",
                            current: true
                        }, true);
                    });
                    AsyncStorage.setItem('token', res.data.Token)
                    props.navigation.navigate('personalInfo')
                }
            }
        } catch (error) {
            Toast.info(error)
        }
        setLoading(false)
    }
    return (
        <View style={styles.footerButton}>
            <ShadowCard style={styles.button}>
                <LinearGradient
                    colors={props.mnemonic.toString() == props.wallet.mnemonic.toString() ? ['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)'] : ["#EDEDED", "#EDEDED"]}
                    start={{ x: 0.25, y: 0.25 }}
                    end={{ x: 0.75, y: 0.75 }}
                    style={[styles.linearGradient]}>
                    <TouchableOpacity type="primary" disabled={props.loading || props.mnemonic.toString() != props.wallet.mnemonic.toString()} style={styles.button} onPress={FinishCreateWallet}>
                        <>
                            {loading ? <ActivityIndicator /> : ""}
                            <Text style={styles.ButtonText}>下一步</Text>
                        </>
                    </TouchableOpacity>
                </LinearGradient>
            </ShadowCard>
        </View >
    )
}
class NewMnemonicPhrase extends Component {
    constructor(props) {
        super(props)
        this.state = {
            loading: false,
            mnemonic: [],
            wallet: props.route.params.wallet,
            shuffleMnemonic: shuffle(JSON.parse(JSON.stringify(props.route.params.wallet.mnemonic)))
        }
    }

    updateState(data) {
        this.setState(data);
    }


    closeMnemonicItem = (i) => {
        const filteredMnemonic = this.state.mnemonic.filter((item, index) => index !== i);
        this.setState({ mnemonic: filteredMnemonic });
    }

    render() {
        return (
            <>
                <View style={styles.page}>
                    <SafeAreaView style={styles.container}>
                        <FlatList
                            data={this.state.mnemonic}
                            renderItem={({ item, index }) => {
                                return (
                                    <Text style={styles.renderItem} onPress={() => this.closeMnemonicItem(index)}>{item}<IconOutline name="close" /></Text>
                                )
                            }}
                            keyExtractor={(item, index) => index}
                            horizontal={false}
                            numColumns={3}
                        />
                    </SafeAreaView>
                    <ShuffleMnemonic shuffleMnemonic={this.state.shuffleMnemonic} mnemonic={this.state.mnemonic} updateParentState={this.updateState.bind(this)} />
                </View>
                <ButtonFinishCreateWallet {...this.props} {...this.state} />

            </>
        )
    }
}

export default connect(mapStateToProps, { SetUserInfo, SetToken })(NewMnemonicPhrase)

const styles = StyleSheet.create({
    page: {
        flex: 1
    },
    text: {
        alignSelf: "center",
        color: "rgba(114, 114, 114, 1)",
        fontSize: pTx(12)
    },
    container: {
        minHeight: pTx(223),
        marginTop: pTx(18),
        marginHorizontal: pTx(35),
        paddingVertical: pTx(15),
        backgroundColor: "rgba(237, 237, 237, 1)",
        borderRadius: 6
    },
    renderItem: {
        marginVertical: pTx(15),
        textAlign: "center",
        flex: 1
    },
    shuffleMnemonic: {
        marginTop: pTx(18),
        marginHorizontal: pTx(35),
        paddingVertical: pTx(15),
        flexDirection: "row",
        flexWrap: "wrap"
    },
    shuffleMnemonicItem: {
        marginHorizontal: pTx(6),
        marginVertical: pTx(6),
        paddingVertical: pTx(6),
        paddingHorizontal: pTx(6),
        fontSize: pTx(13),
        borderWidth: 1,
        borderColor: "#EDEDED",
        borderRadius: 6,
    },

    ButtonText: {
        color: "rgba(10, 12, 20, 1)",
        fontSize: pTx(14),
        fontWeight: 'bold'
    },
    footerButton: {
        paddingTop: pTx(15),
        paddingBottom: pTx(63),
        alignItems: "center"
    },
    linearGradient: {
        borderRadius: 6
    },
    button: {
        width: pTx(303),
        height: pTx(55),
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
    },
    ButtonText: {
        color: "rgba(10, 12, 20, 1)",
        fontSize: pTx(14),
        fontWeight: 'bold'
    },
    itemCurrent: {
        color: "#fff",
        backgroundColor: "rgba(51, 225, 144, 1)",
    }
})